import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;


import com.google.common.base.Function;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.TimeUnit;

public class gaView {
	static WebDriver driver;
	static Wait<WebDriver> wait;
	public static void main(String[] args) {
		/*
		DesiredCapabilities capabilities = DesiredCapabilities.chrome();
		capabilities.setCapability("chrome.binary", "/usr/bin/chromium-browser");
		driver = new ChromeDriver(capabilities);
		*/
		//set Firefox profiles
		FirefoxProfile firefoxProfile = new FirefoxProfile();
		driver = new FirefoxDriver(firefoxProfile);
		//driver = new FirefoxDriver();
		wait = new FluentWait<WebDriver>(driver)
			.withTimeout(30, TimeUnit.SECONDS)
			.pollingEvery(1, TimeUnit.SECONDS)
			.ignoring(org.openqa.selenium.NoSuchElementException.class)
			.ignoring(org.openqa.selenium.NoSuchFrameException.class);
		driver.get("https://gsw8.view.usg.edu");

		try {
			driver.findElement(By.name("webctid")).sendKeys("sbaev");
			driver.findElement(By.name("password")).sendKeys("123456\n");
			System.out.println("Info: Logged in");
			// Wait for APPLICATION_FRAME
			wait.until(
				new Function<WebDriver, WebElement>() {
					public WebElement apply(WebDriver driver) {
						return driver.findElement(By.name("APPLICATION_FRAME"));
					}
				}
			);
			driver = driver.switchTo().frame("APPLICATION_FRAME");
			System.out.println("Info: APPLICATION_FRAME found");
			// Wait for TOOLFRAME			
			wait.until(
				new Function<WebDriver, WebElement>() {
					public WebElement apply(WebDriver driver) {
						return driver.findElement(By.name("TOOLFRAME"));
					}
				}
			);
			driver = driver.switchTo().frame("TOOLFRAME");
			System.out.println("Info: TOOLFRAME found");
			// Wait for the list of courses
			WebElement course = wait.until(
				new Function<WebDriver, WebElement>() {
					public WebElement apply(WebDriver driver) {
						return driver.findElement(By.partialLinkText("UNIX"));
					}
				}
			);
			// Click the course link									
			course.click();
			System.out.println("Info: Course selected");
			// Switch back to "APPLICATION_FRAME"
			driver = driver.switchTo().defaultContent().switchTo().frame("APPLICATION_FRAME");
			System.out.println("Info: APPLICATION_FRAME rediscovered");
			// then to TOOLFRAME
			wait.until(
				new Function<WebDriver, WebElement>() {
					public WebElement apply(WebDriver driver) {
						return driver.findElement(By.name("TOOLFRAME"));
					}
				}
			);
			driver = driver.switchTo().frame("TOOLFRAME");
			System.out.println("Info: TOOLFRAME rediscovered");
			// and finally to RIGHTTOOLFRAME
			wait.until(
				new Function<WebDriver, WebElement>() {
					public WebElement apply(WebDriver driver) {
						return driver.findElement(By.name("RIGHTTOOLFRAME"));
					}
				}
			);
			driver = driver.switchTo().frame("RIGHTTOOLFRAME");
			System.out.println("Info: RIGHTTOOLFRAME found");
			//System.out.println(driver.getPageSource());
			
			wait.until(
				new Function<WebDriver, WebElement>() {
					public WebElement apply(WebDriver driver) {
						return driver.findElement(By.partialLinkText("Quzzes"));
					}
				}
			).click();
			// Retrieve cookies
			Cookie c1 = driver.manage().getCookieNamed("uid2");
			Cookie c2 = driver.manage().getCookieNamed("BIGipServeru4_vista_webapp");
			Cookie c3 = driver.manage().getCookieNamed("JSESSIONIDVISTA");
			String myCookie = String.format("%s=%s; %s=%s; %s=%s",c1.getName(),c1.getValue(),c2.getName(),c2.getValue(), c3.getName(),c3.getValue());
			// Open separate URL connection to the server and pass the obtained cookies			
			URL url = new URL("https://gsw8.view.usg.edu/webct/urw/tp4593330069261.lc4581496208331/RelativeResourceManager/sfsid/4640624213311");
			HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
			httpConn.setAllowUserInteraction(false);
			httpConn.setInstanceFollowRedirects(true);
			httpConn.setRequestMethod("GET");
			httpConn.setConnectTimeout(10000);
			httpConn.setRequestProperty("Cookie", myCookie);
			httpConn.connect();
			/*
			for(int i=0; i<httpConn.getHeaderFields().size(); i++) {
				System.out.printf("%-30s%s\n",httpConn.getHeaderFieldKey(i)+":",httpConn.getHeaderField(i));
			}
			*/
			String fname = httpConn.getHeaderField("Content-Disposition").split("\"",3)[1];
			if(httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				InputStream net_in = httpConn.getInputStream();
				FileOutputStream fid_out = new FileOutputStream("download/" + fname);
				byte buf[]=new byte[1024];
				int len;
				while((len=net_in.read(buf)) > 0)
					fid_out.write(buf,0,len);
				fid_out.close();
				System.out.printf("Info: File '%s' has been downloaded.\n",fname);
			}									
			else {
				System.err.printf("Error: File '%s' cannot be downloaded.\n",fname);
			}
		} 
		catch (java.net.SocketTimeoutException e) {
			System.out.println("Cannot open download link.");
		}		
		catch(Exception e) {
			e.printStackTrace();
		} 
		finally {
			driver.close();
		}	
	}	
}
